package com.meiyou.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.meiyou.pojo.MeiyouHongbao;
import com.meiyou.service.HongBaoService;
import com.meiyou.service.UserService;
import com.meiyou.utils.Msg;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller
@Api(value = "红包控制器", tags = { "红包接口" })
public class HongBaoController {
	@Resource
	private HongBaoService hongBaoServiceImpl;
	@Resource
	private UserService userServiceImpl;

	@RequestMapping(value = "faHongBao", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "发红包")
	public Msg FaHongBao(String hUBcount,  Double hMeijin, HttpServletRequest req) {

		Msg msg;
		if (req.getSession().getAttribute("user") != null) {
			String hUCount = req.getSession().getAttribute("user") + "";
			double meijin = Double.parseDouble(userServiceImpl.selUserByUcount(hUCount));
			if (meijin > hMeijin) {
				MeiyouHongbao meiyouHongbao = new MeiyouHongbao();
				meiyouHongbao.sethMeijin(hMeijin);
				meiyouHongbao.sethState("未接收");
				meiyouHongbao.sethUCount(hUCount);
				meiyouHongbao.sethUBcount(hUBcount);
				int index = hongBaoServiceImpl.insHongBao(meiyouHongbao);
				int hid = meiyouHongbao.gethId();
				
				System.out.println("index:"+index);
				double uMeijin = meijin - hMeijin;
				int upd = userServiceImpl.updUserMeijin(uMeijin, hUCount);
				if (index > 0 && upd > 0) {
					msg = Msg.success();
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("hId", hid);
					msg.setExtend(map);
					return msg;
				}
			}
			return Msg.fail();
		}else {
			msg = Msg.fail();
			msg.setMsg("请先登录");
			return msg;
		}

	}

	@RequestMapping(value = "shouHongBao", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "收红包")
	public Msg ShouHongBao(HttpServletRequest req, int hid) {
		return hongBaoServiceImpl.updHongBao(hid);
	}

}
